<template>
  <el-breadcrumb class="app-breadcrumb" separator=" ">
    <transition-group name="breadcrumb">
      <el-breadcrumb-item v-for="item in levelList" :key="item.path">
        <span v-show="item.meta.showNav" :class="['no-redirect', item.name === $route.matched.at(-1).name ? 'activeColor' : '']" @click="handleLink(item)">{{ item.meta.title }} <i v-show="item.meta.title !== '工作台'" class="delete" @click.stop="deleteRoutes(item.meta.title)">x</i></span>
      </el-breadcrumb-item>
    </transition-group>
  </el-breadcrumb>
</template>

<script>
export default {
  data() {
    return {
      levelList: [
        {
          name: 'dashboard',
          path: '/dashboard',
          meta: {
            title: '工作台',
            showNav: true
          }
        }
      ]
    }
  },
  watch: {
    $route() {
      // console.log(this.$route)
      this.getBreadcrumb()
    }
  },
  created() {
    this.getBreadcrumb()
  },
  methods: {
    getBreadcrumb() {
      if (this.levelList[0].name === this.$route.matched.at(-1).name) {
        this.levelList.splice(0, 1, this.$route.matched.at(-1))
      }
      if (!this.levelList.includes(this.$route.matched.at(-1))) {
        this.levelList.push(this.$route.matched.at(-1))
      }
    },
    // 点击删除
    deleteRoutes(value) {
      const indexItem = this.levelList.findIndex((item) => item.meta.title === value)
      if (value === this.$route.matched.at(-1).meta.title) {
        const delItem = this.levelList[indexItem === 0 ? 0 : indexItem - 1]
        this.levelList = this.levelList.filter((item) => item.meta.title !== value)
        if (this.levelList.length > 1) {
          this.$router.push(delItem.path)
        } else {
          this.$router.push('/')
        }
      } else {
        this.levelList = this.levelList.filter((item) => item.meta.title !== value)
      }
    },
    // 路由跳转
    handleLink(item) {
      console.log(item)
      const { redirect, path } = item
      if (redirect) {
        this.$router.push(redirect)
        return
      }
      this.$router.push(path)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-breadcrumb.el-breadcrumb {
  display: inline-block;
  font-size: 14px;
  line-height: 50px;
  margin-left: 8px;
  max-width: 1500px;
  .no-redirect {
    position: relative;
    color: #97a8be;
    cursor: pointer;
    font-size: 14px;
    // margin: 0 5px;
    height: 25px;
    padding: 5px;
    background-color: rgb(253, 253, 253);
    border-radius: 5px;
    box-shadow: 1px 1px 1px rgb(233, 231, 231);
    .delete {
      display: inline-block;
      margin-left: 5px;
    }
  }
  .activeColor {
    color: orange;
  }
}
</style>
